﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using yzrilyzr.FAQ.client;
using yzrilyzr.FAQ.constants;
using yzrilyzr.FAQ.protocol;
using yzrilyzr.FAQ.utils;

namespace FAQ_UI
{
	/// <summary>
	/// FriendList.xaml 的交互逻辑
	/// </summary>
	public partial class GroupList : Page, MsgPackReceiver
	{
		private List<FAQID> list = new List<FAQID>();

		public GroupList()
		{
			InitializeComponent();
			DataContext = this;
			FAQUtil.client.addReceiver(this);
			update();
		}

		private void update()
		{
			list.Clear();
			foreach (var i in FAQUtil.client.getFriends())
			{
				if (!UUIDs.isPerson(i)) list.Add(i);
			}
			list.Sort((p1, p2) =>
			{
				bool a = FAQClient.isOnline(p1);
				bool b = FAQClient.isOnline(p2);
				if (a == b) return 0;
				if (a) return -1;
				return 1;
			});
		}

		private void Page_Unloaded(object sender, RoutedEventArgs e)
		{
			//FAQUtil.client.removeReceiver(this);
			//FAQUtil.eventBus.removeReceiver(this);
		}

		public List<FAQID> BMsgListDataSource
		{ get { return list; } }

		public Holder BMsgListHolder
		{ get { return new Holder(); } }

		public void onItemClick(object listview, OnItemClickEvent e)
		{
			FAQUtil.eventBus.asyncSend(new BinMsgPack(App.OPEN_CHAT).setTo(list[e.index]));
		}

		public void receive(MsgPackTransfer mpt, MsgPack mp)
		{
			if (mp.isMsg() || mp.getCmd() == C.	USER_CACHE) Dispatcher.Invoke(new Action(() => { myListView.notifyDataChanged(); }));
		}

		public class Holder : FriendHolder
		{
			public override ViewHolder newInstance()
			{
				return new Holder();
			}

			public override void set(int i, object fAQID, IList datalist)
			{
				FAQID faqid = (FAQID)fAQID;
				Name.Text = FAQUtil.getCommNameOrName(faqid);
				Description.Text = FAQUtil.getDescription(faqid);
				Avatar.Drawable = FAQUtil.getAvatar(faqid);
			}
		}
	}
}